package com.kit.data.kitopeso.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kit.data.kitopeso.KitoApp;
import com.kit.data.kitopeso.R;
import com.kit.data.kitopeso.adapter.ContactAdapter;
import com.kit.data.kitopeso.base.BaseActivity;
import com.kit.data.kitopeso.base.BaseDialog;
import com.kit.data.kitopeso.base.BaseParams;
import com.kit.data.kitopeso.databinding.KitoContactActivityBinding;
import com.kit.data.kitopeso.net.PU;
import com.kit.data.kitopeso.net.RxHttp;
import com.kit.data.kitopeso.net.U;
import com.kit.data.kitopeso.obj.KitoContact;
import com.kit.data.kitopeso.obj.KitoContactItem;
import com.kit.data.kitopeso.obj.KitoInfoData;
import com.kit.data.kitopeso.obj.KitoUserProcess;
import com.kit.data.kitopeso.obj.KitoValueInfo;
import com.kit.data.kitopeso.tools.AESCryptUtilJar;
import com.kit.data.kitopeso.tools.JsonParse;
import com.kit.data.kitopeso.tools.LogUtil;
import com.kit.data.kitopeso.tools.NumUtils;
import com.kit.data.kitopeso.tools.PhoneUtils;
import com.kit.data.kitopeso.tools.PopUtils;
import com.kit.data.kitopeso.tools.ResUtils;
import com.kit.data.kitopeso.tools.SpUtils;
import com.kit.data.kitopeso.tools.Tools;
import com.kit.data.kitopeso.tools.ViewUtils;
import com.kit.data.kitopeso.view.KitoSpaceItemDecoration;
import com.kit.data.kitopeso.view.KitoTextView;
import com.xin.data.turning.uitls.ContactHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class KitoContactActivity extends BaseActivity<KitoContactActivityBinding> {

    final String stepTag = "CONTACT_INFO";

    ContactAdapter adater;

    List<KitoContactItem> dataList;

    String stepTitle1;

    String stepTitle2;


    String apiUrl;

    KitoContact contactInfo;
    ContactHelper mContactHelperAType;

    @Override
    protected KitoContactActivityBinding initViewBinding(LayoutInflater inflater) {
        return KitoContactActivityBinding.inflate(inflater);
    }

    @Override
    protected void initView() {

        binding.tvHit1.setText(Html.fromHtml(ResUtils.s(R.string.ocr_hit1)));

        mContactHelperAType = new ContactHelper(this);
        dataList = new ArrayList<>();
        adater = new ContactAdapter(dataList);
        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        manager1.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager1);
        int d1 = ResUtils.d(R.dimen.dp_6);
        binding.recyclerView.addItemDecoration(new KitoSpaceItemDecoration(d1, d1, getActivity()));
        adater.setOnClickSelectInterface((type, position, textView1, textView2) -> {
            KitoContactItem data = dataList.get(position);
            Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot());
            if (type == 2) {
                if (contactInfo != null && contactInfo.getRelationShips() != null && !contactInfo.getRelationShips().isEmpty()) {
                    List<KitoValueInfo> valueBeans;
                    if (position >= contactInfo.getRelationShips().size()) {
                        String[] relationArry = contactInfo.getRelationShips().get(0);
                        valueBeans = getValueList(relationArry);
                    } else {
                        String[] relationArry = contactInfo.getRelationShips().get(position);
                        valueBeans = getValueList(relationArry);
                    }
                    PopUtils.showSelectPop(getActivity(), binding.recyclerView, valueBeans, position, 0, (title, value, position1, index) -> {
                        adater.setError(false);
                        setInfoData(data.getRelationData(), title, value);
                        adater.sendSelectData(data.getRelationData(), textView1);
                    });
                }
            } else if (type == 3) {
                getContactPhone(data, textView1, textView2);
            }
        });
        binding.recyclerView.setAdapter(adater);


        binding.tvBk.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            finish();
        });
        binding.tvCs.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P28 + stepTag + "_KEFU_CLICK", "");
            startActivity(new Intent(getActivity(), KitoCustomerServiceActivity.class));

        });
        binding.tvBtn.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P28 + stepTag + "_SAVE_CLICK", "");
            PU.userBuriedAllPoint(getActivity());
            saveInfo();
        });
        binding.getRoot().setOnClickListener(v -> Tools.hideSoftInputFromWindow(getActivity(), binding.getRoot()));
        binding.tvAdd.setOnClickListener(v -> {
            ViewUtils.viewScale(v);
            PU.userBuriedPoint(PU.P28 + stepTag + "_ADD_CLICK", "");
            KitoContactItem data = addData();
            if (data != null) {
                dataList.add(data);
                adater.updateAllData();
            }
        });

    }

    @Override
    protected void initData() {
        if (KitoApp.getInstance().getProcess() != null) {
            contactInfo = KitoApp.getInstance().getProcess().getContact_info();
            if (contactInfo != null && contactInfo.getDataList() != null && !contactInfo.getDataList().isEmpty()) {
                apiUrl = contactInfo.getApiUrl();
            }
        }
        if (contactInfo != null) {
            for (int i = 0; i < contactInfo.getItemCount(); i++) {
                KitoContactItem data = addData();
                dataList.add(data);
            }
        }
        initStepTitle();
    }


    void setInfoData(KitoInfoData infoData, String title, String value) {
        if (infoData != null && !TextUtils.isEmpty(value)) {
            infoData.setParamValue(value);
        }
        if (infoData != null && !TextUtils.isEmpty(title)) {
            infoData.setParamValueTitle(title);
        }
        adater.updateAllData();
    }

    void getContactPhone(KitoContactItem data, KitoTextView textView1, KitoTextView textView2) {
        mContactHelperAType.pickContactBType((name, phone) -> {
            if (!TextUtils.isEmpty(phone)) {
                phone = phone.replace(" ", "");
                if (phone.contains("(")) {
                    phone = phone.replaceAll("\\(", "");
                }
                if (phone.contains(")")) {
                    phone = phone.replaceAll("\\)", "");
                }
                if (phone.contains("-")) {
                    phone = phone.replaceAll("-", "");
                }
            }
            boolean isAddContactPhone = PhoneUtils.isAddContactPhone(phone, dataList);
            if (isAddContactPhone) {
                showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.contact_info_add_repeat));
            } else {

                LogUtil.e("me", textView1.getClickStartTime() + "--setClickStartTime--" + textView2.getClickStartTime());

                if (textView1.getClickStartTime() > textView2.getClickStartTime()) {
                    textView2.setClickStartTime(textView1.getClickStartTime());
                } else if (textView2.getClickStartTime() > textView1.getClickStartTime()) {
                    textView1.setClickStartTime(textView2.getClickStartTime());
                }
                if (!TextUtils.isEmpty(name)) {
                    name = name.replace(" ", "");
                    setInfoData(data.getFullNameData(), name, name);
                    LogUtil.e("me", name + "--pickContactBType name--" + phone);
                    adater.sendSelectData(data.getFullNameData(), textView1);
                }
                if (!TextUtils.isEmpty(phone)) {
                    phone = phone.replace(" ", "");
                    if (phone.contains("(")) {
                        phone = phone.replaceAll("\\(", "");
                    }
                    if (phone.contains(")")) {
                        phone = phone.replaceAll("\\)", "");
                    }
                    if (phone.contains("-")) {
                        phone = phone.replaceAll("-", "");
                    }
                    adater.setError(false);
                    setInfoData(data.getMobileData(), phone, phone);
                    adater.sendSelectData(data.getMobileData(), textView2);
                    LogUtil.e("me", "--pickContactBType phone--" + phone);
                }
            }
            return null;
        });

    }

    @SuppressLint("SetTextI18n")
    void initStepTitle() {
        stepTitle1 = "";
        stepTitle2 = "";
        KitoUserProcess userProcessBean = KitoApp.getInstance().getProcess();
        if (userProcessBean != null && userProcessBean.getAllSteps() != null && userProcessBean.getAllStepTitles() != null) {
            int index1 = 0;
            int index2 = 0;
            for (int i = 0; i < userProcessBean.getAllSteps().length; i++) {
                String str = userProcessBean.getAllSteps()[i];
                if (str.equals("contact_info")) {
                    index1 = i;
                    break;
                }
            }
            index2=index1+1;
            if (index1 < userProcessBean.getAllStepTitles().length) {
                stepTitle1 = userProcessBean.getAllStepTitles()[index1];
            }
            if (index2 < userProcessBean.getAllStepTitles().length) {
                stepTitle2 = userProcessBean.getAllStepTitles()[index2];
            }
        }

        binding.tvTitle1.setText(stepTitle1);
        binding.tvTitle2.setText(stepTitle2);

        binding.tvNum1.setText("-03");
        binding.tvNum2.setText("-04");


        binding.tvAmount.setVisibility(View.INVISIBLE);
        binding.tvHit.setVisibility(View.VISIBLE);
        binding.tvHit.setText(Html.fromHtml(ResUtils.s(R.string.contact_hit1)));


        double amount = 0;
        String amountstr = SpUtils.get_string(this, SpUtils.KEY_CASH_AMOUNT, "");
        if (!TextUtils.isEmpty(amountstr)) {
            amount = (Double.parseDouble(amountstr) * 0.025);
        }
        binding.tvAmount.setText(getResources().getString(R.string.personal_amount, NumUtils.formatToTwoDecimals(amount)));

        LogUtil.e("me","amount->"+amount);

        adater.setStepTag(stepTag);
        adater.updateAllData();


    }

    void showTipsDialog(String subTitle) {
        showTipsDialog("", "", "", subTitle, true, new BaseDialog.BtnClickListener() {
            @Override
            public void btnOnClickOk() {

            }

            @Override
            public void btnOnClickCancel() {

            }

            @Override
            public void btnOnClickColse() {

            }
        });
    }

    KitoContactItem addData() {
        if (contactInfo != null && contactInfo.getDataList() != null && !contactInfo.getDataList().isEmpty()) {
            KitoContactItem contactInfoData1 = new KitoContactItem();
            KitoInfoData relationData = null;
            KitoInfoData fullNameData = null;
            KitoInfoData mobileData = null;
            for (KitoInfoData infoData : contactInfo.getDataList()) {
                switch (infoData.getAction()) {
                    case "CONTACT_GROUP_RELATION":
                        relationData = getInfoData(infoData);
                        break;
                    case "CONTACT_GROUP_NAME":
                        fullNameData = getInfoData(infoData);
                        break;
                    case "CONTACT_GROUP_PHONE":
                        mobileData = getInfoData(infoData);
                        break;
                }
            }
            if (relationData != null && fullNameData != null && mobileData != null) {
                contactInfoData1.setRelationData(relationData);
                contactInfoData1.setFullNameData(fullNameData);
                contactInfoData1.setMobileData(mobileData);
            }
            return contactInfoData1;
        }
        return null;
    }

    KitoInfoData getInfoData(KitoInfoData infoData) {
        KitoInfoData nData = new KitoInfoData();
        nData.setParamValueTitle(infoData.getParamValueTitle());
        nData.setValues(infoData.getValues());
        nData.setHint(infoData.getHint());
        nData.setTitle(infoData.getTitle());
        nData.setHint_sw(infoData.getHint_sw());
        nData.setTitle_sw(infoData.getTitle_sw());
        nData.setAction(infoData.getAction());
        nData.setParamValue(infoData.getParamValue());
        nData.setIsMust(infoData.getIsMust());
        nData.setParamName(infoData.getParamName());
        return nData;
    }

    List<KitoValueInfo> getValueList(String[] relationArry) {
        List<KitoValueInfo> valueBeans = new ArrayList<>();
        for (String str : relationArry) {
            KitoValueInfo valueBean = new KitoValueInfo();
            valueBean.setValue(str);
            valueBean.setTitle(str);
            valueBeans.add(valueBean);
        }
        return valueBeans;
    }

    void saveInfo() {
        if (contactInfo == null) {
            showTipsDialog(getResources().getString(R.string.not_completely_tips));
            adater.setError(true);
            adater.updateAllData();
            return;
        }
        if (dataList.size() < contactInfo.getItemCount()) {
            showTipsDialog(getResources().getString(R.string.contact_info_itemcount, String.valueOf(contactInfo.getItemCount())));
            adater.setError(true);
            adater.updateAllData();
            return;
        }

        int itemCount = 0;
        for (int i = 0; i < dataList.size(); i++) {
            KitoContactItem data = dataList.get(i);
            KitoInfoData relationData = data.getRelationData();
            KitoInfoData fullNameData = data.getFullNameData();
            KitoInfoData mobileData = data.getMobileData();
            if (relationData != null && fullNameData != null && mobileData != null) {

                boolean isTxt1 = false;
                boolean isTxt2 = false;
                boolean isTxt3 = false;

                if (!TextUtils.isEmpty(relationData.getIsMust()) && relationData.getIsMust().equals("YES")) {
                    if (!TextUtils.isEmpty(relationData.getParamValue())) {
                        if (relationData.getParamValue().equalsIgnoreCase(ResUtils.s(R.string.other))) {
                            if (!TextUtils.isEmpty(relationData.getOther())) {
                                isTxt1 = true;
                            }
                        } else {
                            isTxt1 = true;
                        }
                    }
                } else {
                    isTxt1 = true;
                }

                if (!TextUtils.isEmpty(fullNameData.getIsMust()) && fullNameData.getIsMust().equals("YES")) {
                    if (!TextUtils.isEmpty(fullNameData.getParamValue())) {
                        isTxt2 = true;
                    }
                } else {
                    isTxt2 = true;
                }

                if (!TextUtils.isEmpty(mobileData.getIsMust()) && mobileData.getIsMust().equals("YES")) {
                    if (!TextUtils.isEmpty(mobileData.getParamValue())) {
                        isTxt3 = true;
                    }
                } else {
                    isTxt3 = true;
                }

                if (isTxt1 && isTxt2 && isTxt3) {
                    itemCount = itemCount + 1;
                }

            }
        }

        LogUtil.e("me", "itemCount->" + itemCount);


        if (itemCount < contactInfo.getItemCount()) {
            showTipsDialog(getResources().getString(R.string.not_completely_tips));
            adater.setError(true);
            adater.updateAllData();
            return;
        }


        if (!TextUtils.isEmpty(apiUrl) && apiUrl.contains("/")) {
            apiUrl = apiUrl.replaceAll("/", "");
        }
        JsonArray contactParamBeanList = new JsonArray();

        JsonObject json = BaseParams.getJsonObject(getActivity(), apiUrl);
        for (int i = 0; i < dataList.size(); i++) {
            KitoContactItem data = dataList.get(i);
            KitoInfoData relationData = data.getRelationData();
            KitoInfoData fullNameData = data.getFullNameData();
            KitoInfoData mobileData = data.getMobileData();
            if (!TextUtils.isEmpty(relationData.getParamValue()) && !TextUtils.isEmpty(fullNameData.getParamValue()) && !TextUtils.isEmpty(mobileData.getParamValue())) {
                JsonObject jsonObject = getJsonObject(relationData, fullNameData, mobileData);
                contactParamBeanList.add(jsonObject);
            }
        }
        if (contactParamBeanList.size() < contactInfo.getItemCount()) {
            showTipsDialog(getResources().getString(R.string.contact_info_itemcount, String.valueOf(contactInfo.getItemCount())));
            adater.setError(true);
            adater.updateAllData();
            return;
        }

        showLoading("");

        String str = contactParamBeanList.toString();
        LogUtil.e("me", dataList.size() + "<-getContactParamName->" + str);
        json.addProperty(contactInfo.getContactParamName(), str);
        HashMap<String, String> heads = new HashMap<>();
        heads.put("product", U.URL_PRODUCT);
        if (!TextUtils.isEmpty(U.URL_COUNTRY)) {
            heads.put("country", U.URL_COUNTRY);
        }
        String data = AESCryptUtilJar.encryptDefault(json.toString());
        LogUtil.e("me", json + "<-saveInfo post->" + data);
        RxHttp.post(U.commonUrl, data, heads)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull String s) {
                        if (!TextUtils.isEmpty(s)) {
                            String json1 = AESCryptUtilJar.decryptDefault(s);
                            LogUtil.e("me", "saveInfo json->" + json1);
                            if (JsonParse.getCode(json1)) {
                                userProcess(() -> {
                                    boolean isCheckSteps = checkSteps();
                                    if (!isCheckSteps) {
                                        startActivity(new Intent(getActivity(), KitoApplyActivity.class));
                                    }
                                    finish();
                                }, true);
                            } else {
                                showToastDialog(R.mipmap.hit_icon, JsonParse.getMsg(getActivity(), json1));
                            }

                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        hideLoading();
                        showToastDialog(R.mipmap.hit_icon, getResources().getString(R.string.login_faile));
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    @NonNull
    private static JsonObject getJsonObject(KitoInfoData relationData, KitoInfoData fullNameData, KitoInfoData mobileData) {
        JsonObject jsonObject = new JsonObject();
        if (relationData.getParamValue().equalsIgnoreCase(ResUtils.s(R.string.other))) {
            jsonObject.addProperty(relationData.getParamName(), relationData.getOther());
        } else {
            jsonObject.addProperty(relationData.getParamName(), relationData.getParamValue());
        }
        jsonObject.addProperty(fullNameData.getParamName(), fullNameData.getParamValue());
        jsonObject.addProperty(mobileData.getParamName(), mobileData.getParamValue());
        return jsonObject;
    }

    @Override
    protected void onResume() {
        super.onResume();
        PU.userBuriedPoint(PU.P28 + stepTag + "_START", "");

    }

    @Override
    protected void onPause() {
        super.onPause();
        PU.userBuriedPoint(PU.P28 + stepTag + "_END", "");
    }



}
